/**
 * com.monte.web.framework.controller.EditController.java
 * create by FengMy from 2013
 */
package com.monte.web.framework.controller;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;

import com.monte.entity.CoreEntity;
import com.monte.service.BaseService;
import com.monte.util.BeanUtils;
import com.monte.util.StringUtils;

/**
 * @描述: 编辑页面Controller
 * @author FengMy
 * @since 2013-3-26
 */
public abstract class EditController extends BaseController {
	@SuppressWarnings("unchecked")
	@RequestMapping(value="save")
	public void save(HttpServletResponse response) throws InstantiationException, IllegalAccessException{
		Object data = getSubmitEntity();
		if(validate(data)){
			if(data instanceof CoreEntity){
				if(StringUtils.isEmpty(((CoreEntity)data).getId())){
					getService().addEntity((CoreEntity)data);
				}else{
					getService().updateEntity((CoreEntity)data);
				}
				getOutputMsg().put("id", ((CoreEntity)data).getId());
				getOutputMsg().put("STATE", "SUCCESS");
				getOutputMsg().put("MSG", "保存成功");
			}
		}else{
			getOutputMsg().put("STATE", "FAIL");
		}
		outPrint(response, JSONObject.fromObject(getOutputMsg(), getDefaultJsonConfig()));
	}
	
	protected boolean validate(Object data) {
		return true;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Object getSubmitEntity(){
		Class c = getSubmitClass();
		if(c==null){
			return null;
		}
		String id = getString("id");
		Object entity = null;
		if(!StringUtils.isEmpty(id)){
			entity = getService().getEntityById(id);
		}
		entity = BeanUtils.fillentity(getParamMap(),entity, c);
		return entity;
	}
	
	@SuppressWarnings("rawtypes")
	protected abstract Class getSubmitClass();

	/**
	 * 获取Service
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected abstract BaseService getService();
}
